package com.baiyue.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baiyue.entity.ProductInfo;
import com.baiyue.exception.GlobalException;
import com.baiyue.mapper.ProductInfoMapper;
import com.baiyue.model.productInfo.ProductInfoDataRequest;
import com.baiyue.model.productInfo.ProductInfoDataResponse;
import com.baiyue.model.tollRules.TollRulesDataResponse;
import com.baiyue.result.CodeMsg;
import com.baiyue.service.ProductInfoService;
import com.baiyue.utils.BeanMapperUtil;
import com.baiyue.utils.UserHolderUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Wrapper;
import java.util.*;

/**
 *
 * @author 伍波
 * @date 2024-06-13
 */
@Service
public class ProductInfoServiceImpl implements ProductInfoService {
    private static final Logger logger = LoggerFactory.getLogger(ProductInfoServiceImpl.class);

    @Autowired
    private ProductInfoMapper productInfoMapper;

    /**
     * 新增商品详情
     * @param request
     */
    @Override
    public void insert(ProductInfoDataRequest request){
        logger.info("新增商品信息入参:{}", JSONObject.toJSONString(request));
        if (StringUtils.isEmpty(request.getProductName())){
            logger.warn("商品信息商品名称入参为空");
            throw new GlobalException(CodeMsg.BIND_ERROR.fillArgs("商品名称"));
        }
        if (Objects.nonNull(findByProductName(request.getProductName()))){
            logger.warn("商品名称已存在，请核查后再试");
            throw new GlobalException(CodeMsg.ALREADY_EXISTS.fillArgs("商品名称"));
        }
        String user = UserHolderUtil.getUser().getUsername();
        request.setCreator(user);
        request.setUpdater(user);
        request.setCreateTime(new Date());
        request.setUpdateTime(new Date());
        if (Objects.isNull(request.getStatus())){
            request.setStatus(0);
        }
        ProductInfo productInfo = BeanMapperUtil.map(request, ProductInfo.class);
        productInfoMapper.insert(productInfo);
    }

    /**
     * 分页查询信息
     * @param request
     * @return
     */
    @Override
    public Page<ProductInfoDataResponse> findByPage(ProductInfoDataRequest request){
        logger.info("查询商品信息列表入参:{}", JSONObject.toJSONString(request));
        Page<ProductInfoDataResponse> responsePage = new Page<>(request.getPage(),request.getSize());

        ProductInfo productInfo = BeanMapperUtil.map(request, ProductInfo.class);
        List<ProductInfo> productInfoList = productInfoMapper.findByPage(productInfo,responsePage);
        List<ProductInfoDataResponse> responseList = BeanMapperUtil.mapList(productInfoList, ProductInfoDataResponse.class);
        return responsePage.setRecords(responseList);
    }

    /**
     *根据商品名称查询信息
     * @param productName
     * @return
     */
    public ProductInfo findByProductName(String productName){
        if (StringUtils.isEmpty(productName)){
            logger.warn("根据商品名称查询商品信息失败：商品名称为空");
            throw new GlobalException(CodeMsg.BIND_ERROR.fillArgs("ProductName"));
        }
        return productInfoMapper.findByProductName(productName);
    }

    /**
     * 根据id查询商品信息
     * @param request
     * @return
     */
    @Override
    public ProductInfoDataResponse findById(ProductInfoDataRequest request){
        if (Objects.isNull(request.getId())){
            logger.warn("根据id查询异常！！！id为空");
            throw new GlobalException(CodeMsg.BIND_ERROR.fillArgs("id"));
        }
        ProductInfo productInfo = productInfoMapper.selectById(request.getId());
        logger.info("根据id查询商品信息出参：{}", JSONObject.toJSONString(productInfo));
        return BeanMapperUtil.map(productInfo, ProductInfoDataResponse.class);
    }

    /**
     * 删除商品信息
     * @param request
     * @return
     */
    @Override
    public Boolean deleteByIds(ProductInfoDataRequest request){
        logger.info("删除商品信息入参:{}", JSONObject.toJSONString(request));
        Objects.requireNonNull(request.getIds(), () -> {
            logger.error("删除商品信息失败：ids不可为空");
            return "删除商品信息失败";
        });
        String user = UserHolderUtil.getUser().getUsername();
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("idList",request.getIds());
        paramMap.put("updateBy",user);
        Integer res = productInfoMapper.deleteByIds(paramMap);
        return res == request.getIds().size();
    }

    /**
     * 修改商品信息
     * @param request
     */
    @Override
    public void updateProductInfo(ProductInfoDataRequest request){
        logger.info("修改商品信息入参:{}", JSONObject.toJSONString(request));
        if (StringUtils.isEmpty(request.getProductName())){
            logger.warn("修改商品信息商品名称入参为空");
            throw new GlobalException(CodeMsg.BIND_ERROR.fillArgs("商品名称"));
        }
        ProductInfo res = findByProductName(request.getProductName());
        if (Objects.nonNull(res) && !Objects.equals(request.getId(), res.getId())){
            logger.warn("修改商品名称已存在，请核查后再试");
            throw new GlobalException(CodeMsg.ALREADY_EXISTS.fillArgs("商品名称"));
        }

        String user = UserHolderUtil.getUser().getUsername();
        request.setUpdater(user);
        request.setUpdateTime(new Date());
        ProductInfo productInfo = BeanMapperUtil.map(request, ProductInfo.class);
        productInfoMapper.updateById(productInfo);
    }

    /**
     * 不分页查询所有商品信息
     * @param request
     * @return
     */
    @Override
    public List<ProductInfoDataResponse> findAllNoPage(ProductInfoDataRequest request){
        logger.info("获取所有商品信息不分页入参:{}", JSONObject.toJSONString(request));
        ProductInfo productInfo = BeanMapperUtil.map(request, ProductInfo.class);
        List<ProductInfo> list = productInfoMapper.findByPage(productInfo);
        return BeanMapperUtil.mapList(list, ProductInfoDataResponse.class);
    }
}
